# Test is there any significant aggretive pattern left in fittedModel
# @fittedModel: An agMobject or its extensions after modeled by covariances
# @nsim:        number of simulation times used in evenlop function
# Author: guochun
###############################################################################


agregativeResidualTest=function(fittedModel,nsim){
	data.ppp=populationToppp(fittedModel@population)
	if(length(fittedModel@covr)!=0){
		e=envelope(data.ppp,fun=pcf,simulate=expression(rpoispp(attr(fittedModel,"trend"))),
				savefuns=TRUE,r=seq(0,60,2),nsim=nsim,verbose=FALSE)
	}else{
		e=envelope(data.ppp,fun=pcf,verbose=FALSE,
				savefuns=TRUE,r=seq(0,60,2),nsim=nsim)
	}
	npp=nsim+1
	Kfuns=attr(e,"simfuns")
	n=length(e$obs)
	Kfuns[,1]=e$obs
	ui=vector("numeric",npp)
	for (k in 2:(n-1)){
		Kit=Kfuns[k,]
		t.rslt=step.ui(Kit,2,npp)
		ui = ui+t.rslt
	}
	attr(fittedModel,"global_pForD")=calc.pval(ui)
	return(fittedModel)
}


######################################################################
calc.pval <- function(ui)
{
	# fetch the ui for the observed pattern
	my.ui <- ui[1]
	# calculate the number of values greater than the observed
	my.pval <- (length(ui[ui>=my.ui]))/(length(ui))
	
	return(my.pval)
}

#######################################################################
step.ui <- function(Kit, delta.t, npp, c=0.25)
{
	Ki.bar <- (sum(Kit) - Kit)/(npp-1)
	
	this.ui <- (Kit^c-Ki.bar^c) *
			(Kit^c-Ki.bar^c) * delta.t
	
	
	ui.step <- vector("numeric", npp)
	ui.step <- ui.step + this.ui
	
	return(ui.step)
}



